package cn.edu.sdjzu.xg21.dao;

import cn.edu.sdjzu.xg21.domain.School;
import cn.edu.sdjzu.xg21.exception.BysjException;
import cn.edu.sdjzu.xg21.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SchoolDao {
    // 将唯一的构造器（无参构造器）私有化，放置在本类外生成本类的对象
    private SchoolDao(){}
    private static SchoolDao schoolDao = null;
    // 返回本类的唯一对象
    public static SchoolDao getInstance(){
        // 静态变量schoolDao为null时，才创建SchoolDao对象
        // 第二次或者后来调用本方法schoolDao就不为null了，故不再创建对象
        if(schoolDao == null){
            schoolDao = new SchoolDao();
        }
        return schoolDao;
    }

    // 根据指定的id,从表中找到相应的行,并将本行元组映射为对象
    // 不能是静态的，因为实际上是实现了接口的方法
    public School find(Integer id) throws SQLException, BysjException {
        // 创建School类型的引用，暂不创建对象
        School desiredSchool = null;
        // 获取数据库俩捏
        Connection connection = JdbcHelper.getConn();
        String sql_select_id = "SELECT * FROM school WHERE id=?";
        PreparedStatement pstmt_select_id = connection.prepareStatement(sql_select_id);
        pstmt_select_id.setInt(1,id);
        ResultSet resultSet_select_id = pstmt_select_id.executeQuery();
        // 如果表中存在id对应的元组，则获得表中的字段值，并创建对象
        if (resultSet_select_id.next()){
            String description = resultSet_select_id.getString("description");
            String no = resultSet_select_id.getString("no");
            String remarks = resultSet_select_id.getString("remarks");
            desiredSchool = new School(id,description,no,remarks);
        }
        // 关闭三个资源
        JdbcHelper.close(resultSet_select_id,pstmt_select_id,connection);
        return desiredSchool;
    }
}
